import React, { useEffect, useState } from 'react'
import { Button, Descriptions, message } from 'antd';
import axios from 'axios';
import moment from 'moment'
import { HeartTwoTone } from '@ant-design/icons';


export default function Detail(props) {
  const [newData, setNewData] = useState(null)
  // 获取指定id的新闻
  useEffect(() => {
    // console.log(props.match.params.id)
    axios.get(`news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
      // console.log(res.data)
      setNewData({
        ...res.data,
        view: res.data.view + 1
      })
      return res.data
    }).then(res => {
      // 增加浏览量
      axios.patch(`news/${props.match.params.id}`, {
        view: res.view + 1
      })
    })
  }, [props.match.params.id])

  // 点赞新闻
  const likeNew = () => {
    setNewData({
      ...newData,
      star: newData.star + 1
    })

    axios.patch(`news/${props.match.params.id}`, {
      star: newData.star + 1
    }).then(res => {
      message.success('点赞成功')
    })
  }
  return (
    <div style={{ padding: '40px' }}>
      <Button type='primary' onClick={() => props.history.goBack()}>返回</Button>
      {newData && <div style={{ paddingTop: 20 }}>
        <Descriptions title={<div>{newData.title}----<span>{newData.category.title}</span>  <HeartTwoTone twoToneColor="#eb2f96" onClick={() => likeNew()} /></div>} >
          <Descriptions.Item label="创建者">{newData.author}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{moment(newData.createTime).format('YYYY/MM/DD HH:mm:ss')}</Descriptions.Item>
          <Descriptions.Item label="发布时间">{newData.publishTime ? moment(newData.publishTime).format('YYYY/MM/DD HH:mm:ss') : '暂无'}</Descriptions.Item>
          <Descriptions.Item label="区域">{newData.region}</Descriptions.Item>
          <Descriptions.Item label="访问数量">{newData.view}</Descriptions.Item>
          <Descriptions.Item label="点赞数量">{newData.star}</Descriptions.Item>
          <Descriptions.Item label="评论数量">0</Descriptions.Item>
        </Descriptions >
        <h1 style={{ marginBottom: 20 }}>新闻内容</h1>
        <div dangerouslySetInnerHTML={{
          __html: newData.content
        }}></div>
      </div>}
    </div>

  )
}
